//
//  DaishouScanViewController.m
//  TengyunStation
//
//  Created by Johnny on 15/11/13.
//  Copyright © 2015年 xingrong. All rights reserved.
//

#import "DaishouScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "TSHeader.h"
#import "ZBarSDK.h"
#import "DaishouExpress.h"
#import "ShowAlertView.h"
#import "DSToast.h"

@interface DaishouScanViewController ()<ZBarReaderViewDelegate,ShowAlertViewDelegate> {
    BOOL _isDownScroll;//判断是否向上滚动
    NSTimer *_timer;    
    ZBarReaderView *_readerView;
}

@end

@implementation DaishouScanViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = @"二维码/条码";
        _isDownScroll = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //监听应用进入活跃状态
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    [self performSelector:@selector(setZBarSDK) withObject:nil afterDelay:0.5];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [_timer invalidate];
}

- (void)setZBarSDK {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    _readerView = [[ZBarReaderView alloc] init];
    _readerView.device = device;
    _readerView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    _readerView.readerDelegate = self;
    _readerView.tracksSymbols = NO;
//    _readerView.enableCache = NO;
    //关闭闪光灯
    _readerView.torchMode = 0;
    [self.view insertSubview:_readerView atIndex:0];
    [_readerView start];
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(lineUpOrDownScroll) userInfo:nil repeats:YES];
    _lineImageView.hidden = NO;
    [_activityView stopAnimating];
    _activityView.hidden = YES;
}

-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds {
    CGFloat x,y,width,height;
    x = rect.origin.x / readerViewBounds.size.width;
    y = rect.origin.y / readerViewBounds.size.height;
    width = rect.size.width / readerViewBounds.size.width;
    height = rect.size.height / readerViewBounds.size.height;
    return CGRectMake(x, y, width, height);
}

- (void)lineUpOrDownScroll {
    float y = _lineImageView.frame.origin.y;
    if (_isDownScroll) {
        y += 1.5;
        if (y >= 275) {
            _isDownScroll = NO;
        }
    } else {
        y -= 1.5;
        if (y <= 63) {
            _isDownScroll = YES;
        }
    }
    _lineImageView.frame = CGRectMake(_lineImageView.frame.origin.x, y, _lineImageView.frame.size.width, _lineImageView.frame.size.height);
}

- (void)stopScanning {
    [_timer invalidate];
    _lineImageView.hidden = YES;
    _readerView.readerDelegate = nil;
}

- (void)startScanning {
    _lineImageView.hidden = NO;
    _readerView.readerDelegate = self;
    if (![_timer isValid]) {
        _timer = [[NSTimer alloc] initWithFireDate:[NSDate date] interval:0.02 target:self selector:@selector(lineUpOrDownScroll) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

//通知
- (void)didBecomActive {
    [_readerView start];
}

#pragma mark ZBarReaderViewDelegate
- (void)readerView:(ZBarReaderView *)readerView didReadSymbols:(ZBarSymbolSet *)symbols fromImage:(UIImage *)image {
    for (ZBarSymbol *symbol in symbols) {
        BOOL isExit = NO;
        for (DaishouExpress *express in self.expressList) {
            if ([express.expressId isEqualToString:symbol.data]) {
                isExit = YES;
                [self showAlertView:express];
                break;
            }
        }
        if (!isExit) {
            [DSToast showText:@"该运单号不在此批次。" InView:self.view ShowType:DSToastShowTypeScanShow];
        }
        break;
    }
}

- (void)showAlertView:(DaishouExpress *)express {
    [self stopScanning];
    ShowAlertView *alert = [[ShowAlertView alloc] initWithDaishouExpress:express];
    alert.delegate = self;
    [alert show];
}

#pragma mark ShowAlertViewDelegate
- (void)cancelAlertView {
    [self startScanning];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

@end
